﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;

//保证lua解析器的唯一性
public class LuaMgr : Singleton<LuaMgr>
{
    private LuaEnv _luaEnv;
    public LuaEnv luaEnv => _luaEnv;

    public LuaTable Global => luaEnv.Global;
    
    public void Init()
    {
        if (_luaEnv != null) return;

        _luaEnv = new LuaEnv();
        _luaEnv.AddLoader(LuaLoader);
        //_luaEnv.AddLoader(ABLoader);
    }

    public void DoLuaFile(string fileName)
    {
        var str = string.Format("require('{0}')", fileName);
        DoString(str);
    }
    
    public void DoString(string str)
    {
        if (_luaEnv == null)
        {
            Debug.LogWarning("解析器未初始化");
            //Init()
            return;
        }
        _luaEnv.DoString(str);
    }

    public void Tick()
    {
        if (_luaEnv == null)
        {
            Debug.LogWarning("解析器未初始化");
            //Init()
            return;
        }
        _luaEnv.Tick();
    }

    public void Dispose()
    {
        if (_luaEnv == null)
        {
            Debug.LogWarning("解析器未初始化");
            //Init()
            return;
        }
        _luaEnv.Dispose();
        _luaEnv = null;
    }

    private byte[] LuaLoader(ref string filePath)
    {
        if (filePath.Equals("emmy_core"))
        {
            Debug.Log("重定向跳过emmy_core");
            return null;
        }
        
        var path = Application.dataPath + "/Lua/" + filePath + ".lua";
        var path2 = Application.dataPath + "/Lua/LuaCallCSharp/" + filePath + ".lua";
        var path3 = Application.dataPath + "/Lua/XLuaBag/" + filePath + ".lua";
        var path4 = Application.dataPath + "/Lua/Hotfix/" + filePath + ".lua";

        if (File.Exists(path))
        {
            Debug.Log("require(加载):"+filePath);
            return File.ReadAllBytes(path);
        }
        else if(File.Exists(path2))
        {
            Debug.Log("require(加载):"+filePath);
            return File.ReadAllBytes(path2);
        }
        else if(File.Exists(path3))
        {
            Debug.Log("require(加载):"+filePath);
            return File.ReadAllBytes(path3);
        }
        else if(File.Exists(path4))
        {
            Debug.Log("require(加载):"+filePath);
            return File.ReadAllBytes(path4);
        }
        else
        {
            Debug.Log("LuaLoader重定向失败，文件名为"+filePath);
        }
        
        return null;
    }
    
    private byte[] ABLoader(ref string filePath)
    {
        if (filePath.Equals("emmy_core"))
        {
            Debug.Log("重定向跳过emmy_core");
            return null;
        }
        
        var luaAsset = ABMgr.GetInstance().LoadRes<TextAsset>("lua", filePath + ".lua");
        if (luaAsset != null)
        {
            return luaAsset.bytes;
        }
        else
        {
            Debug.Log("ABLoader重定向失败，文件名为"+filePath);
        }
        
        return null;
    }
}
